package com.wjx.zk

import org.apache.curator.framework.CuratorFramework
import org.apache.curator.framework.CuratorFrameworkFactory
import org.apache.curator.framework.api.BackgroundCallback
import org.apache.curator.retry.ExponentialBackoffRetry
import org.apache.zookeeper.CreateMode
import org.apache.zookeeper.data.Stat
import java.util.concurrent.CountDownLatch

fun main(args: Array<String>) {
    val countDownLatch = CountDownLatch(1)
    val test = CuratorTest()
    test.createClient()

    countDownLatch.await()
}

class CuratorTest {
    fun createClient(): CuratorFramework {
        val retryPolicy = ExponentialBackoffRetry(1000, 3)
        val zk = CuratorFrameworkFactory.builder()
                .connectString("192.168.11.128:2182,192.168.11.128:2183,192.168.11.128:2184")
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace("curator")
                .build()
        zk.start()
        println("zk start")

        zk.create().forPath("/test1")
        zk.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/test1/test1", "test".toByteArray())
        val stat = Stat()
        println("get data: ${String(zk.data.storingStatIn(stat).forPath("/test1/test1"))} ,stat version:${stat.version}")
        zk.setData().forPath("/test1/test1", "test2".toByteArray())
        zk.delete().guaranteed().deletingChildrenIfNeeded().forPath("/test1")//guaranteed 会在后台不断重试，保证删除

        zk.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .inBackground(BackgroundCallback { client, event ->
                    println("client:$client,eventType:${event.type},eventCode:${event.resultCode}")
                }).forPath("/test1")
        return zk
    }

}
